﻿using Infragistics.WebUI.UltraWebGrid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ParameterDTO;
using uMES.LeanManufacturing.ReportBusiness;
using Newtonsoft.Json;
using uMES.LeanManufacturing.DBUtility;

public partial class MaterialRawApplyPopupForm : BaseForm
{
    uMESMaterialBusiness material = new uMESMaterialBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    uMESCommonBusiness common = new uMESCommonBusiness();
    string businessName = "生产准备", parentName = "materialappinfo";
    protected void Page_Load(object sender, EventArgs e)
    {
        WebPanel = WebAsyncRefreshPanel1;

        if (!IsPostBack)
        {
            if (Session["PopupData"] != null) {

                DataTable dt = Session["PopupData"] as DataTable;
                dt.Columns.AddRange(new[] { new DataColumn("processquota"),new DataColumn("numberofblank") ,new DataColumn("IsSendErp"), new DataColumn("FLQty"),
                new DataColumn("ApplyClQty")});
                foreach (DataRow dr in dt.Rows) {
                    DealRowData(dr);
                }
                wgRawMaterial.DataSource = dt;
                wgRawMaterial.DataBind();


                //hdPopoupData.Value = JsonConvert.SerializeObject(dt);
            }

        }
    }

    protected void btnMaterialApp_Click(object sender, EventArgs e)
    {
        try {
            var re = SaveData();
            if (re.IsSuccess == false) {
                DisplayMessage(lStatusMessage, re.Message, false);
                return;
            }
            //LoadFlMaterialData();
            ClosePopupPage(true);
        } catch (Exception ex) {
            DisplayMessage(lStatusMessage, ex.Message + "：" + ex.StackTrace.Substring(ex.StackTrace.IndexOf("行号")), false);
        }
    }

    protected void btnClose_Click(object sender, EventArgs e)
    {
        ClosePopupPage(false);
    }
    /// <summary>
    /// 校验数据
    /// </summary>
    /// <returns></returns>
    ResultModel CheckData(DataTable dt) {
        ResultModel re = new ResultModel(true,"");
        foreach (DataRow dr in dt.Rows) {
            if (string.IsNullOrWhiteSpace(dr["processquota"].ToString()) || string.IsNullOrWhiteSpace(dr["numberofblank"].ToString()))
            {
                return new ResultModel(false, "工艺定额信息不能为空");
            }
            //containerBal.GetTableInfo("materialappinfo", "dispatchinfoid", dr["ID"]
            if (common .QueryDataByEntity (new ExcuteEntity("materialappinfo", ExcuteType.selectAll) { WhereFileds = new List<FieldEntity>() { new FieldEntity("dispatchinfoid", dr["ID"].ToString(), FieldType.Str),
                    new FieldEntity("issenderp",5, FieldType.Numer) } }).Rows.Count>0) {
                return new ResultModel(false, "有记录已有反馈成功的物料申请记录");
            }
            //如果有erp代料名称则需要判断是否挂附件
            if (!dr.IsNull("ReplaceMaterialName")) {
                if (containerBal.GetTableInfo("ckattachment", "ContainerID",dr["ContainerID"].ToString()).Rows.Count==0) {
                    return new ResultModel(false, "批次"+dr["ContainerName"].ToString()+"有erp代料信息，需要挂附件才能申请物料!");
                }
            }
        }

        return re;

    }
    /// <summary>
    /// 保存数据
    /// </summary>
    /// <returns></returns>
    ResultModel SaveData() {
        ResultModel re = new ResultModel(false, "");
        DataTable dt = uMESCommonFunction.GetGridData(wgRawMaterial);
        re = CheckData(dt);

        if (re.IsSuccess == false)
            return re;

        foreach (DataRow dr in dt.Rows) {
            addMaterialAppData(dr);
        }

        re.IsSuccess = true;
        return re;
    }

    /// <summary>
    /// 加载发料信息
    /// </summary>
    void LoadFlMaterialData() {
        string dispatchId = wgRawMaterial.Rows[0].Cells.FromKey("DispatchID").Text;
        DataTable flDt = material.GetMaterialSendByDispatchId(dispatchId);
        if (flDt.Rows.Count == 0) {
            return;
        }

        txtFlQty.Text = flDt.Rows[0]["Qty"].ToString();

    }

    /// <summary>
    /// 二次处理弹出的每行数据
    /// </summary>
    /// <param name="row"></param>
    void DealRowData(DataRow dr) {
       
        //Dictionary<string, string> para = Session["PopupData"] as Dictionary<string, string>;

        DataTable productDt = containerBal.GetTableInfo("Product", "productid", dr["ProductID"]);

        DataTable workflowDt = containerBal.GetTableInfo("Workflow", "WorkflowID", dr["WorkflowID"]);

        DataTable materialDt = containerBal.GetTableInfo("materialappinfo", "dispatchinfoid", dr["ID"]);

        DataTable flDt = material.GetMaterialSendByDispatchId(dr["ID"].ToString());

        dr["processquota"] = workflowDt.Rows[0]["processquota"];
        dr["numberofblank"] = workflowDt.Rows[0]["numberofblank"];

        if (materialDt.Rows.Count == 0)
        {
            dr["IsSendErp"] = "否";
        }
        else
        {
            if (materialDt.Rows[0]["issenderp"].ToString() == "1")
            {
                dr["IsSendErp"] = "是";
            }
            else
            {
                dr["IsSendErp"] = "否";
            }
        }
        if (flDt.Rows.Count >0)
            dr["FLQty"]= flDt.Rows[0]["Qty"].ToString();

        decimal processquota = 0; int numberofblank = 0;
        if (!string.IsNullOrWhiteSpace(workflowDt.Rows[0]["processquota"].ToString()))
        {
            processquota = Convert.ToDecimal(workflowDt.Rows[0]["processquota"]);
        }
        if (!string.IsNullOrWhiteSpace(workflowDt.Rows[0]["numberofblank"].ToString()))
        {
            numberofblank = Convert.ToInt32(workflowDt.Rows[0]["numberofblank"]);
        }
        if (dr.IsNull("ReplaceMaterialName"))
            dr["ApplyClQty"] = Convert.ToInt32(dr["Qty"]) * processquota;/// numberofblank;
        else
            dr["ApplyClQty"] = dr["ReplaceMaterialQty"];


    }

    /// <summary>
    /// 添加每行的申请领料数据
    /// </summary>
    /// <param name="dr"></param>
    void addMaterialAppData(DataRow dr) {
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        //如果已经申请过
        //如果已经申请，则只需更新issendErp字段
        DataTable materialDt = common.QueryDataByEntity(new ExcuteEntity("materialappinfo", ExcuteType.selectAll) {
            WhereFileds = new List<FieldEntity>() { new FieldEntity("dispatchinfoid", dr["ID"].ToString(),FieldType.Str) }
        });
        if (materialDt.Rows.Count > 0)
        {
            common.ExecuteDataByEntity(new ExcuteEntity("materialappinfo", ExcuteType.update)
            {
                ExcuteFileds = new List<FieldEntity>() { new FieldEntity("issenderp", "0", FieldType.Str), new FieldEntity("erpreturnmsg", "", FieldType.Str) },
                WhereFileds = new List<FieldEntity>() { new FieldEntity("dispatchinfoid", dr["ID"].ToString(), FieldType.Str) }
            });
            
            #region 记录日志
            var ml2 = new MESAuditLog();
            ml2.ContainerName = dr["ContainerName"].ToString(); ml2.ContainerID = dr["ContainerID"].ToString();
            ml2.ParentID = materialDt.Rows[0]["ID"].ToString(); ml2.ParentName = parentName;
            ml2.CreateEmployeeID = userInfo["EmployeeID"];
            ml2.BusinessName = businessName; ml2.OperationType = 1;
            ml2.Description = "物料申请:" + "零件物料申请";
            common.SaveMESAuditLog(ml2);
            #endregion
            return;
        }


        Dictionary<string, string> para = new Dictionary<string, string>();
        string strID = Guid.NewGuid().ToString();
        string strMaterialAppInfoName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        para.Add("MaterialAppInfoID", strID);
        para.Add("MaterialAppInfoName", strMaterialAppInfoName);
        para.Add("DispatchInfoID",dr["ID"].ToString());
        para.Add("ContainerID",dr["ContainerID"].ToString());
        para.Add("ContainerName",dr["ContainerName"].ToString());
        para.Add("SpecID",dr["SpecID"].ToString());
        para.Add("SpecNo", "");
        para.Add("SpecName", "");
        para.Add("FactoryID", userInfo["FactoryID"]);
        para.Add("ProcessNo",dr["ProcessNo"].ToString());
        para.Add("OprNo", "");
        para.Add("Type", "0");
        para.Add("SubmitEmployeeID", userInfo["EmployeeID"]);

        para.Add("MfgorderName",dr["MfgOrderName"].ToString());
        para.Add("ProductID",dr["ProductID"].ToString());
        para.Add("Qty",dr["Qty"].ToString());
        para.Add("WorkflowID",dr["WorkflowID"].ToString());

        string strSubmitDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        para.Add("SubmitDate", strSubmitDate);
        para.Add("Status", "0");
        para.Add("Notes", ""); para["AppType"] = "0";

        material.AddMaterialAppInfo(para, new DataTable());

        #region 记录日志
        var ml = new MESAuditLog();
        ml.ContainerName = dr["ContainerName"].ToString(); ml.ContainerID = dr["ContainerID"].ToString();
        ml.ParentID = strID; ml.ParentName = parentName;
        ml.CreateEmployeeID = userInfo["EmployeeID"];
        ml.BusinessName = businessName; ml.OperationType = 0;
        ml.Description = "物料申请:" +"零件物料申请";
        common.SaveMESAuditLog(ml);
        #endregion
    }
}